import { getBusinessProjectFilePath } from "../utils/index.js";
import fs from "fs";
import getPkgToolsConfig from "../utils/getPkgToolsConfig.js";
import { argv } from "../utils/npmTag.js";
const { outputDir } = await getPkgToolsConfig();

/**
 * 向dist/README.md 添加 changelog
 */
const appendChangelog = () => {
  const dir = argv["skip-compile"] ? "./" : outputDir;
  const changelogPath = getBusinessProjectFilePath("./CHANGELOG.md");
  if (!fs.existsSync(changelogPath)) {
    console.log("未找到 CHANGELOG.md，跳过 Append changelog...");
    return;
  }
  console.log("Append changelog...");
  const readmeFilePath = getBusinessProjectFilePath("./README.md");
  let readme = "";
  if (fs.existsSync(readmeFilePath)) {
    readme = fs.readFileSync(getBusinessProjectFilePath("./README.md"));
  }
  fs.writeFileSync(getBusinessProjectFilePath(`./${dir}/README.md`), readme, {
    encoding: "utf8",
  });

  if (!argv["skip-compile"]) {
    fs.appendFileSync(
      getBusinessProjectFilePath(`./${dir}/README.md`),
      `# 更新日志 \n`,
      { encoding: "utf8" }
    );
  }

  fs.appendFileSync(
    getBusinessProjectFilePath(`./${dir}/README.md`),
    `${fs.readFileSync(changelogPath)}`,
    { encoding: "utf8" }
  );
};
export default appendChangelog;
